<script setup lang="ts">
import SimpleTab from "@/components/simple-tab/SimpleTab.vue";
import SimpleDialog from "@/components/simple-dialog/SimpleDialog.vue";
import { ref } from "vue";
import {
  type WebsiteConfiguration,
  type EmailConfiguration,
  type ArticleConfiguration,
  type RSSConfiguration,
  type TwikooConfiguration,
  type BaiduTongjiConfiguration,
  type WechatConfiguration,
  updateWebsiteConfiguration,
  updateEmailConfiguration,
  updateArticleConfiguration,
  updateRSSConfiguration,
  updateTwikooConfiguration,
  updateWechatConfiguration,
  updateBaiduTongjiConfigurations,
  type Configuration,
} from "@/api/configuration";
import { ResponseStatus } from "@/api/request";
import { useConfigurationStore } from "@/stores/stores";


const loadComplete = ref(false);
let configuration: Partial<Configuration> | any | undefined;
useConfigurationStore()
  .getConfiguration()
  .then((c) => {
    configuration = c;
    loadComplete.value = true;
    setTimeout(() => {
      activeTabIndex.value = 1;
    }, 0);
    setTimeout(() => {
      activeTabIndex.value = 0;
    }, 0);
  });
loadComplete.value = true;
const tabs = ref([
  "基本设置",
  "文章设置",
  "评论设置",
  "RSS设置",
  "邮箱设置",
  "统计设置",
  "微信公众号设置",
]);
const activeTabIndex = ref(0);
const websiteSettingSchema = ref([
  {
    $formkit: "text",
    label: "LOGO",
    name: "logo",
  },
  {
    $formkit: "text",
    label: "站点名称",
    name: "name",
    validation: "required|length:1,16",
  },
  {
    $formkit: "text",
    label: "站点描述",
    name: "description",
  },
  {
    $formkit: "url",
    label: "站点链接",
    name: "url",
    placeholder: "https://www.example.com",
  },
  {
    $formkit: "text",
    label: "版本",
    name: "version",
  },
  {
    $formkit: "text",
    label: "copyright",
    name: "copyright",
  },
  {
    $formkit: "datetime-local",
    label: "建站时间",
    name: "setUpTime",
    placeholder: "2024-01-01",
  },
  {
    $formkit: "text",
    label: "ICP备案",
    name: "ICP备案",
    placeholder: "XICP备XXXXXXXXXX号-X",
  },
  {
    $formkit: "text",
    label: "公网安备案",
    name: "公网安备案",
    placeholder: "X公网安备XXXXXXXXXXXXXX",
  },
  {
    $formkit: "text",
    label: "萌ICP备案号",
    name: "萌ICP备案号",
    placeholder: "20244202",
  },
]);
const articleSettingSchema = ref([
  {
    $formkit: "checkbox",
    label: "启用文章点赞功能",
    name: "enableLike",
    value: true,
  },
  {
    $el: "h2",
    children: "文章归档",
    attrs: {
      class: "text-xl font-bold mb-4",
    },
  },
  {
    $formkit: "number",
    label: "文章归档更新周期（分钟）",
    name: "archiveUpdateInterval",
    number: "integer",
    validation: "required|numeric|min:1",
    value: 60 * 24, // 24小时
  },
]);
const commentSettingSchema = ref([
  {
    $el: "h2",
    children: "默认评论功能",
    attrs: {
      class: "text-xl font-bold mb-4",
    },
  },
  {
    $formkit: "checkbox",
    label: "启用评论",
    name: "enableComment",
    value: true,
  },
  {
    $formkit: "checkbox",
    label: "启用评论审核（站长无需审核）",
    name: "enableCommentReview",
    value: false,
  },
  {
    $el: "h2",
    children: "Twikoo",
    attrs: {
      class: "text-xl font-bold mb-4",
    },
  },
  {
    $formkit: "checkbox",
    label: "启用Twikoo",
    name: "enableTwikoo",
    value: false,
    help: "优先级更高",
  },
  {
    $formkit: "text",
    label: "Twikoo环境ID",
    name: "twikooEnvID",
    value: "",
  },
  {
    $formkit: "select",
    label: "Twikoo环境地域",
    name: "twikooRegion",
    help: "腾讯云环境填 ap-shanghai 或 ap-guangzhou",
    options: [
      {
        label: "",
        value: "",
      },
      {
        label: "ap-shanghai",
        value: "ap-shanghai",
      },
      {
        label: "ap-beijing",
        value: "ap-beijing",
      },
    ],
  },
  {
    $formkit: "select",
    label: "Twikoo语言",
    name: "twikooLang",
    options: [
      {
        label: "中文",
        value: "zh",
      },
      {
        label: "简体中文",
        value: "zh-cn",
      },
      {
        label: "English",
        value: "en",
      },
    ],
  },
]);
const rssSettingSchema = ref([
  {
    $formkit: "checkbox",
    label: "启用RSS",
    name: "enable",
    value: true,
  },
  {
    $formkit: "number",
    label: "更新周期（分钟）",
    name: "updateInterval",
    number: "integer",
    value: 60 * 12, // 12小时
  },
]);
const emailSettingSchema = ref([
  {
    $formkit: "checkbox",
    label: "启用邮件功能",
    name: "enable",
    value: false,
    help: "用于发送验证码与评论通知",
  },
  {
    $formkit: "checkbox",
    label: "secure",
    name: "secure",
    help: "true for port 465, false for all other ports",
    value: false,
  },
  {
    $formkit: "url",
    label: "SMTP服务器",
    name: "host",
    // validation: "required",
    value: "",
  },
  {
    $formkit: "number",
    label: "SMTP端口",
    name: "port",
    number: "integer",
    validation: "numeric|min:1|max:65535",
  },
  {
    $formkit: "text",
    label: "邮箱用户",
    name: "user",
    // validation: "required",
    value: "",
  },
  {
    $formkit: "password",
    label: "邮箱密码",
    name: "pass",
    // validation: "required",
    value: "",
  },
]);
const wechatSettingSchema = ref([
  {
    $formkit: "text",
    label: "微信公众号APPID",
    name: "appID",
    value: "",
  },
  {
    $formkit: "password",
    label: "微信公众号APPSecret",
    name: "appSecret",
    value: "",
  },
]);
function changeTab(info: { activeIndex: number; activeTab: string }) {
  console.log(info);
  activeTabIndex.value = info.activeIndex;
}
async function updateWebsiteSetting(formData: Partial<WebsiteConfiguration>) {
  console.log(formData);
  const result = await updateWebsiteConfiguration(formData);
  alert(result.message);
  if (result.status === ResponseStatus.SUCCESS && configuration) {
    Object.assign(configuration.website!, formData);
  }
}
async function updateArticleSetting(formData: Partial<ArticleConfiguration>) {
  console.log(formData);
  const result = await updateArticleConfiguration(formData);
  alert(result.message);
  if (result.status === ResponseStatus.SUCCESS && configuration) {
    Object.assign(configuration.article!, formData);
  }
}
async function updateCommentSetting(formData: any) {
  console.log(formData);
  const c1: Partial<ArticleConfiguration> = {
    enableComment: formData.enableComment,
    enableCommentReview: formData.enableCommentReview,
  };
  const c2: TwikooConfiguration = {
    enable: formData.enableTwikoo,
    envID: formData.twikooEnvID,
    region: formData.twikooRegion,
    lang: formData.twikooLang,
  };
  const result1 = await updateArticleConfiguration(c1);
  const result2 = await updateTwikooConfiguration(c2);
  if (result1.status === ResponseStatus.SUCCESS && result2.type === ResponseStatus.SUCCESS) {
    alert("更新配置成功");
    if (configuration) {
      Object.assign(configuration.article!, c1);
      configuration.twikoo = c2;
    }
  } else {
    alert("更新配置失败");
  }
}
async function updateRSSSetting(formData: Partial<RSSConfiguration>) {
  console.log(formData);
  const result = await updateRSSConfiguration(formData);
  alert(result.message);
  if (result.status === ResponseStatus.SUCCESS && configuration) {
    Object.assign(configuration.rss!, formData);
  }
}
async function updateEmailSetting(formData: Partial<EmailConfiguration>) {
  console.log(formData);
  const result = await updateEmailConfiguration(formData);
  alert(result.message);
  if (result.status === ResponseStatus.SUCCESS && configuration) {
    Object.assign(configuration.email!, formData);
  }
}
async function updateWechatSetting(formData: Partial<WechatConfiguration>) {
  console.log(formData);
  const result = await updateWechatConfiguration(formData);
  alert(result.message);
  if (result.status === ResponseStatus.SUCCESS && configuration) {
    Object.assign(configuration.wechat!, formData);
  }
}

const addBaitduTongjiDialog = ref();
function showAddBaiduTongjiSettingDialog() {
  addBaitduTongjiDialog.value.show();
}
async function addBaiduTngjiSetting(formData: BaiduTongjiConfiguration) {
  console.log(formData);
  if (!configuration || !configuration.tongji) {
    alert("发生错误");
    return;
  }
  const nc = [...configuration.tongji.baidu, formData];
  const result = await updateBaiduTongjiConfigurations(nc);
  if (result.status === ResponseStatus.SUCCESS) {
    configuration.tongji.baidu = nc;
    alert("新增成功")
    addBaitduTongjiDialog.value.hide();
  } else {
    alert("新增失败");
  }
}
async function deleteBaiduTongjiSetting(index: number) {
  if (!window.confirm("是否删除")) {
    return;
  }
  const baiduTongjiConfiguration = configuration?.tongji?.baidu;
  if (!baiduTongjiConfiguration) {
    alert("发生错误");
    return;
  }

  const nc = [];
  for (let i = 0; i < baiduTongjiConfiguration.length; i++) {
    if (i === index) {
      continue;
    }
    nc.push(baiduTongjiConfiguration[i]);
  }

  const result = await updateBaiduTongjiConfigurations(nc);
  if (result.status === ResponseStatus.SUCCESS) {
    configuration!.tongji!.baidu = nc;
    alert("删除成功");
  } else {
    alert("删除失败");
  }
}

</script>

<template>
  <div
    class="border rounded overflow-hidden h-full flex flex-col"
    v-if="loadComplete"
  >
    <SimpleTab :tabs="tabs" @change="changeTab"></SimpleTab>
    <div class="flex-1 bg-base-100 box-border p-4">
      <!-- 基本设置 -->
      <div
        role="tabpanel"
        class="bg-base-100 border-base-300 rounded-box"
        v-if="activeTabIndex === 0"
      >
        <FormKit
          type="form"
          :value="configuration?.website"
          submit-label="保存"
          @submit="updateWebsiteSetting"
        >
          <FormKitSchema :schema="websiteSettingSchema"></FormKitSchema>
        </FormKit>
      </div>

      <!-- 文章设置 -->
      <div
        role="tabpanel"
        class="bg-base-100 border-base-300 rounded-box"
        v-if="activeTabIndex === 1"
      >
        <FormKit
          type="form"
          :value="configuration?.article"
          submit-label="保存"
          @submit="updateArticleSetting"
        >
          <FormKitSchema :schema="articleSettingSchema"></FormKitSchema>
        </FormKit>
      </div>

      <!-- 评论设置 -->
      <div
        role="tabpanel"
        class="bg-base-100 border-base-300 rounded-box"
        v-if="activeTabIndex === 2"
      >
        <FormKit
          type="form"
          :value="{
            enableComment: configuration?.article?.enableComment,
            enableCommentReview: configuration?.article?.enableCommentReview,
            enableTwikoo: configuration?.twikoo?.enable,
            twikooEnvID: configuration?.twikoo?.envID,
            twikooRegion: configuration?.twikoo?.region,
            twikooLang: configuration?.twikoo?.lang
          }"
          submit-label="保存"
          @submit="updateCommentSetting"
        >
          <FormKitSchema :schema="commentSettingSchema"></FormKitSchema>
        </FormKit>
      </div>

      <!-- RSS设置 -->
      <div
        role="tabpanel"
        class="bg-base-100 border-base-300 rounded-box"
        v-if="activeTabIndex === 3"
      >
        <FormKit
          type="form"
          :value="configuration?.rss"
          submit-label="保存"
          @submit="updateRSSSetting"
        >
          <FormKitSchema :schema="rssSettingSchema"></FormKitSchema>
        </FormKit>
      </div>

      <!-- 邮箱设置 -->
      <div
        role="tabpanel"
        class="bg-base-100 border-base-300 rounded-box"
        v-if="activeTabIndex === 4"
      >
        <FormKit
          type="form"
          :value="configuration?.email"
          submit-label="保存"
          @submit="updateEmailSetting"
        >
          <FormKitSchema :schema="emailSettingSchema"></FormKitSchema>
        </FormKit>
      </div>

      <!-- 统计设置 -->
      <div
          role="tabpanel"
          class="bg-base-100 border-base-300 rounded-box"
          v-if="activeTabIndex === 5"
      >
        <div>
          <div class="flex flex-col gap-2 my-4">
            <!--  -->
            <div class="flex justify-between items-center">
              <h2 class="text-xl font-bold">百度统计</h2>
              <button class="btn" @click="showAddBaiduTongjiSettingDialog">新增</button>
            </div>
            <!-- 数据展示表格 -->
            <div class="overflow-x-auto">
              <table class="table text-center border-2">
                <thead>
                  <tr>
                    <th></th>
                    <th>域名</th>
                    <th>code</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr
                    class="hover"
                    v-for="(item, index) in configuration?.tongji?.baidu"
                    :key="index"
                  >
                    <th>{{ index }}</th>
                    <td>{{ item.domain }}</td>
                    <td>{{ item.code }}</td>
                    <td>
                      <button
                        class="btn btn-outline btn-error"
                        @click="deleteBaiduTongjiSetting(index)"
                      >
                        删除
                      </button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            <!-- 新增数据dialog -->
            <SimpleDialog
              ref="addBaitduTongjiDialog"
              title="新增"
              @hide="$formkit.reset('form-add-baidu-tongji')"
            >
              <FormKit
                id="form-add-baidu-tongji"
                type="form"
                submit-label="确定"
                :submit-attrs="{
                  inputClass: 'w-full flex justify-center',
                  wrapperClass: 'flex items-center justify-center',
                  ignore: false,
                }"
                @submit="addBaiduTngjiSetting"
              >
                <FormKit type="text" name="domain" label="域名" validation="required"></FormKit>
                <FormKit type="text" name="code" label="code" validation="required"></FormKit>
              </FormKit>
            </SimpleDialog>
          </div>
        </div>
      </div>

      <!-- 微信设置 -->
      <div
        role="tabpanel"
        class="bg-base-100 border-base-300 rounded-box"
        v-if="activeTabIndex === 6"
      >
        <FormKit
          type="form"
          :value="configuration?.wechat"
          submit-label="保存"
          @submit="updateWechatSetting"
        >
          <FormKitSchema :schema="wechatSettingSchema"></FormKitSchema>
        </FormKit>
      </div>
    </div>
  </div>
</template>
